<template>
    <div class="container">
      <!-- 头部区域 -->
      <van-nav-bar title="小思同学" left-arrow @click-left="onClickLeft"  />

      <!-- 聊天区域 -->
      <div class="chat-list">
        <div v-for="(item,index) in list" :key="index">
          <!-- 左边是机器人小思 -->
          <div class="left chat-item" v-if="item.name!=='me'">
            <!-- 头像 -->
            <van-image round  src="https://img01.yzcdn.cn/vant/cat.jpeg" />
            <div class="chat-pao">{{item.message}}</div>
          </div>

          <!-- 右边是当前用户 -->
          <div class="right chat-item" v-else>
            <div class="chat-pao">{{item.message}} </div>
            <!-- 头像 -->
            <van-image round :src="$store.state.user.photo"/>
          </div>
        </div>

        <!-- 对话框 -->
        <div class="reply-container van-hairline--top">
           <van-field v-model="value" placeholder="请输入消息" >
            <template #button>
              <van-button size="small" type="primary" @click="sendMessage">发送</van-button>
            </template>
           </van-field>
        </div>
      </div>
    </div>
</template>

<script>
import { io } from 'socket.io-client'
import { getToken } from '@/utils/token'
export default {
  name: 'myChat',
  data () {
    return {
      // 对话框输入的值
      value: '',
      // 所有消息对象
      list: [
        { name: 'xs', message: 'Hi,你今天在干嘛？' },
        { name: 'me', message: '哈哈哈，我在吃饭' },
        { name: 'xs', message: 'Hi,你今天在干嘛？' },
        { name: 'me', message: '哈哈哈，我在吃饭' },
        { name: 'xs', message: 'Hi,你今天在干嘛？' },
        { name: 'xs', message: 'Hi,你今天在干嘛？' },
        { name: 'me', message: '哈哈哈，我在吃饭' },
        { name: 'xs', message: 'Hi,你今天在干嘛？' },
        { name: 'xs', message: 'Hi,你今天在干嘛？' },
        { name: 'xs', message: 'Hi,你今天在干嘛？' },
        { name: 'me', message: '哈哈哈，我在吃饭' }
      ],
      socket: null
    }
  },
  created () {
    this.connectSocket()
    this.getMessage()
    console.log(this.$store.state.user)
  },
  destroyed () {
    this.socket.close()
    this.socket = null
  },

  methods: {

    // 头部的左箭头返回事件
    onClickLeft () {
      this.$router.back()
    },
    // 建立连接
    connectSocket () {
      this.socket = io('ws://geek.itheima.net', {
        query: {
          token: getToken()
        },
        transports: ['websocket']
      })
    },
    // 自动滚动到聊天的最底部
    scrollToBottom () {
      const chatItem = document.querySelectorAll('.chat-item')
      const lastItem = chatItem[chatItem.length - 1]
      lastItem.scrollIntoView({
        behavior: 'smooth'
      })
    },
    // 获取服务端发送的消息
    getMessage () {
      // 接收消息
      this.socket.on('message', data => {
        // 把服务器发送过来的消息，存储到list数组中
        this.list.push({
          name: 'xs',
          message: data.msg
        })
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      })
    },

    // 发送消息
    sendMessage () {
      if (!this.value.trim()) return
      // 把我的消息添加到数组中
      this.list.push({
        name: 'me',
        message: this.value
      })
      // 发送给服务端
      this.socket.emit('message', {
        msg: this.value,
        timestamp: new Date().getTime()
      })
      // 清空文本框的内容
      this.value = ''
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    }

  }
}
</script>

<style lang="less" scoped>
.van-nav-bar{
  background-color: #007bff;
  position: fixed;
  width: 100%;
  top: 0;
}
/deep/ .van-nav-bar__title,
/deep/ .van-icon-arrow-left:before
{
  color:#fff;
}
.container{
  width: 100%;
  height: 100%;
  position: absolute;
  left:0;
  top: 0;
  box-sizing: border-box;
  background-color: #fafafa;
  padding: 46px 0 50px 0;
  .chat-list{
    height: 100%;
    overflow-y:scroll ;
    .chat-item{
      padding: 10px;
      .van-image{
        vertical-align: top;
        width: 40px;
        height: 40px;
      }
      .chat-pao{
        vertical-align: top;
        display: inline-block;
        min-width: 40px;
        max-width: 70%;
        min-height: 35px;
        font-size: 15px;
        border: 0.5px solid #c2d9ea;
        border-radius: 4px;
        position: relative;
        padding: 0 10px;
        background-color: #e0effb;
        word-break: break-all;
        color: #333;
        &::before{
          content: '';
          width: 10px;
          height: 10px;
          position: absolute;
          top: 12px;
          border-top: 0.5px solid #c2d9ea;
          border-right: 0.5px solid #c2d9ea;
          background-color: #e0effb;
        }
      }
    }
    .left{
      text-align: left;
      .chat-pao{
        margin-left: 15px;
        margin-right: 0;
        &::before{
          left:-5px;
          transform: rotate(-135deg);
        }
      }
    }
    .right{
      text-align: right;
      .chat-pao{
        margin-right: 15px;
        margin-left: 0;
        text-align: left;
        &::before{
          right: -5px;
          transform: rotate(45deg);
        }
      }
    }
  }
}

//底部对话框
.reply-container{
  position: fixed;
  left:0;
  bottom: 0;
  width: 100%;
  height: 44px;
  background-color: #f5f5f5;
  z-index: 9999;
}
</style>
